package cn.wjssl.domain.activity.service.partake;

import cn.wjssl.domain.activity.model.aggregate.CreatePartakeOrderAggregate;
import cn.wjssl.domain.activity.model.entity.*;
import cn.wjssl.domain.activity.model.valobj.UserRaffleOrderStateVO;
import cn.wjssl.domain.activity.repository.IActivityRepository;
import cn.wjssl.types.enums.ResponseCode;
import cn.wjssl.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
public class RaffleActivityPartakeService extends AbstractRaffleActivityPartake{

    // 定义时间格式, 用于对应数据库中Day, Month
    private final SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM");
    private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private IActivityRepository repository;

    // 校验账户信息, 查询是否有月账户, 日账户, 总账户是否还有抽奖次数, 返回聚合对象
    @Override
    protected CreatePartakeOrderAggregate doFilterAccount(String userId, Long activityId, Date currentDate) {
        // 查询总账户
        ActivityAccountEntity accountEntity = repository.queryActivityAccountByUserId(userId, activityId);
        // 额度判断（只判断总剩余额度）
        if (null == accountEntity || accountEntity.getTotalCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
        }

        String month = dateFormatMonth.format(currentDate);
        String day = dateFormatDay.format(currentDate);

        // 查询月账户额度
        ActivityAccountMonthEntity accountMonthEntity = repository.queryActivityAccountMonthByUserId(userId, activityId, month);
        if (null != accountMonthEntity && accountMonthEntity.getMonthCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
        }

        // 创建月账户额度；这里判断的是 accountMonthEntity 不是null ?
        // 如果存在accountMonthEntity, 那么就是true
        // 如果不存在, 就是false
        boolean isExistAccountMonth = null != accountMonthEntity;
        if (null == accountMonthEntity) {
            accountMonthEntity = new ActivityAccountMonthEntity();
            accountMonthEntity.setUserId(userId);
            accountMonthEntity.setActivityId(activityId);
            accountMonthEntity.setMonth(month);
            accountMonthEntity.setMonthCount(accountEntity.getMonthCount());
            // accountMonthEntity.setMonthCountSurplus(accountEntity.getMonthCount());
            accountMonthEntity.setMonthCountSurplus(accountEntity.getMonthCountSurplus());
        }

        // 日账户 和 月账户 处理方式相同
        ActivityAccountDayEntity accountDayEntity = repository.queryActivityAccountDayByUserId(userId, activityId, day);
        if (null != accountDayEntity && accountDayEntity.getDayCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());
        }

        // 创建月账户额度；true = 存在月账户、false = 不存在月账户
        boolean isExistAccountDay = null != accountDayEntity;
        if (null == accountDayEntity) {
            accountDayEntity = new ActivityAccountDayEntity();
            accountDayEntity.setUserId(userId);
            accountDayEntity.setActivityId(activityId);
            accountDayEntity.setDay(day);
            accountDayEntity.setDayCount(accountEntity.getDayCount());
            // accountDayEntity.setDayCountSurplus(accountEntity.getDayCount());
             accountDayEntity.setDayCountSurplus(accountEntity.getDayCountSurplus());
        }

        // 创建订单聚合对象
        CreatePartakeOrderAggregate createPartakeOrderAggregate = new CreatePartakeOrderAggregate();
        createPartakeOrderAggregate.setUserId(userId);
        createPartakeOrderAggregate.setActivityId(activityId);
        createPartakeOrderAggregate.setActivityAccountEntity(accountEntity);
        createPartakeOrderAggregate.setExistAccountMonth(isExistAccountMonth);
        createPartakeOrderAggregate.setActivityAccountMonthEntity(accountMonthEntity);
        createPartakeOrderAggregate.setExistAccountDay(isExistAccountDay);
        createPartakeOrderAggregate.setActivityAccountDayEntity(accountDayEntity);

        // 返回聚合对象
        return createPartakeOrderAggregate;
    }

    // 创建订单实体, 用于填充聚合对象
    @Override
    protected UserRaffleOrderEntity buildUserRaffleOrder(String userId, Long activityId, Date currentDate) {
        // 查询活动信息
        ActivityEntity activityEntity = repository.queryRaffleActivityByActivityId(activityId);
        // 创建订单
        UserRaffleOrderEntity userRaffleOrder = new UserRaffleOrderEntity();
        userRaffleOrder.setUserId(userId);
        userRaffleOrder.setActivityId(activityId);
        userRaffleOrder.setActivityName(activityEntity.getActivityName());
        userRaffleOrder.setStrategyId(activityEntity.getStrategyId());
        userRaffleOrder.setOrderId(RandomStringUtils.randomNumeric(12));
        userRaffleOrder.setOrderTime(currentDate);
        userRaffleOrder.setOrderState(UserRaffleOrderStateVO.create);
        userRaffleOrder.setEndDateTime(activityEntity.getEndDateTime());
        return userRaffleOrder;
    }
}
